import { createI18n } from "vue-i18n";
import type {App} from 'vue'

import vuetify from "@Plugins/vuetify"

import { ls } from '@Plugins/storage';

// import { changeEditorLang } from "@Plugins/wang-editor/index.ts"

import zhCn from "./lang/zh-cn";
import zhHk from "./lang/zh-hk";
import en from "./lang/en";

import langList from "./langList"

const DEFAULT_LANG = 'en';
const LOCALE_KEY = 'localeLanguage';
let lang = ls.get(LOCALE_KEY) || DEFAULT_LANG;

const localeslist = JSON.parse(ls.get('currentCompanyLanguage'));

let keys = <any>{};
keys = {
  "zh-cn": {...zhCn},
  "zh-hk": {...zhHk},
  "en": {...en}
};

const _i18n = createI18n({
  legacy: false,
    locale: lang,
    fallbackLocale: DEFAULT_LANG,
    messages: keys,
    silentTranslationWarn: true
})

// 切换语言
export const setup_locale = (_lang:any) => {
    if (!_lang) {
        _lang = ls.get(LOCALE_KEY);
        if (keys[_lang] === undefined) {
            lang = DEFAULT_LANG;
        }
    }
    ls.set(LOCALE_KEY, _lang);
    // UI框架切换语言
    vuetify.locale.current.value = _lang;
    // 编辑器切换语言
    // changeEditorLang(_lang);
    _i18n.global.locale = _lang;
}

setup_locale(ls.get(LOCALE_KEY) || DEFAULT_LANG);

function _t(text:string, obj:any = {}) {
    // 匹配开头
    if (text.startsWith('btn_') || text.startsWith('label_') || text.startsWith('text_') || text.startsWith('title_') || text.startsWith('i18n_') || text.startsWith('tip_')) {
        return _i18n.global.t(text, obj);
    }
    return text;
}

export default (app:App)=>{
    app.use(_i18n);
    app.config.globalProperties.$t = _t;
}

export const i18n = _i18n;
export const t = _t;
